import GoogleMobileAds

protocol AppOpenAdManagerDelegate: AnyObject {
    /// 当开屏广告的生命周期完成（即被关闭或未能展示）时调用的方法。
    func appOpenAdManagerAdDidComplete(_ appOpenAdManager: AppOpenAdManager)
    
}

class AppOpenAdManager: NSObject ,ObservableObject{
    
    weak var delegate: AppOpenAdManagerDelegate?
    @Published var adClosed = false
    var advalue  = ""
    var myAdSourceId = ""
    var myadID = ""
    var mycu = ""
    var myci = ""
    

    let timeoutInterval: TimeInterval = 4 * 3_600

    var appOpenAd: GADAppOpenAd?
   
    weak var appOpenAdManagerDelegate: AppOpenAdManagerDelegate?
    
    var isLoadingAd = false
  
    var isShowingAd = false
  
    var loadTime: Date?
    
    static let shared = AppOpenAdManager()
    
    private func wasLoadTimeLessThanNHoursAgo(timeoutInterval: TimeInterval) -> Bool {
      
        if let loadTime = loadTime {
            return Date().timeIntervalSince(loadTime) < timeoutInterval
        }
        return false
    }
    
    private func isAdAvailable() -> Bool {
    
        return appOpenAd != nil && wasLoadTimeLessThanNHoursAgo(timeoutInterval: timeoutInterval)
    }
    
    private func appOpenAdManagerAdDidComplete() {
    
        appOpenAdManagerDelegate?.appOpenAdManagerAdDidComplete(self)
    }
    
    func loadAd() async {
      
        if isLoadingAd || isAdAvailable() {
            return
        }
        isLoadingAd = true
        
        adLog("开始加载开屏广告。")
        
        do {
            appOpenAd = try await GADAppOpenAd.load(
                withAdUnitID: openId, request: GADRequest())
            appOpenAd?.fullScreenContentDelegate = self
            loadTime = Date()
        } catch {
            appOpenAd = nil
            loadTime = nil
            adDidClose()
          //logData(position: "open error", status: "开屏广告", uid: self.myadID, info: "开屏广告加载失败", currency: "", cicros: "",errorInfo :" \(error.localizedDescription)")

            adLog("开屏广告加载失败，错误：\(error.localizedDescription)")
        }
        isLoadingAd = false
    }
    
    func showAdIfAvailable() {
       
        if isShowingAd {
            adLog("开屏广告已经在展示。")
            return
        }
       
        if !isAdAvailable() {
            adLog("开屏广告尚未准备好。")
            appOpenAdManagerAdDidComplete()
            if GoogleMobileAdsConsentManager.shared.canRequestAds {
                Task {
                    await loadAd()
                }
            }
            return
        }
        if let ad = appOpenAd {
            self.appOpenAd = ad
            self.appOpenAd?.paidEventHandler = { adValue in
                // 提取展示级广告收入数据
                let value = adValue.value
            
                let precision = adValue.precision
                let currencyCode = adValue.currencyCode
                
                // 获取广告单元 ID
                let adUnitId = ad.adUnitID
                
                let responseInfo = ad.responseInfo
                let loadedAdNetworkResponseInfo = responseInfo.loadedAdNetworkResponseInfo
                let adSourceId = loadedAdNetworkResponseInfo?.adSourceID
                let adSourceInstanceId = loadedAdNetworkResponseInfo?.adSourceInstanceID
                let adSourceInstanceName = loadedAdNetworkResponseInfo?.adSourceInstanceName
                let adSourceName = loadedAdNetworkResponseInfo?.adSourceName
                let mediationGroupName = responseInfo.extrasDictionary["mediation_group_name"]
                let mediationABTestName = responseInfo.extrasDictionary["mediation_ab_test_name"]
                let mediationABTestVariant = responseInfo.extrasDictionary["mediation_ab_test_variant"]
                
                
                self.advalue  = "\(value)"
                self.myAdSourceId = "\(adSourceId ?? "null")"
                if let adSourceId = adSourceId {
                    adLog(" 广告来源 ID: \(adSourceId)") // 输出广告来源 ID
                    self.myadID = adSourceId

                }
                self.mycu = currencyCode
                self.myci = "\(value)"
                adLog("*****************开屏广告数据***************************")

                // 输出获取的信息
                adLog(" 广告价值: \(value)") // 输出广告价值
                adLog(" 精度: \(precision)") // 输出广告收入的精度
                adLog(" 货币代码: \(currencyCode)") // 输出货币代码
                adLog(" 广告单元 ID: \(adUnitId)") // 输出广告单元 ID
                
                if let adSourceInstanceId = adSourceInstanceId {
                  //  adLog("xianban: 广告来源实例 ID: \(adSourceInstanceId)") // 输出广告来源实例 ID
                }
                if let adSourceInstanceName = adSourceInstanceName {
                 //   adLog(" 广告来源实例名称: \(adSourceInstanceName)") // 输出广告来源实例名称
                }
                if let adSourceName = adSourceName {
                   // adLog("xianban: 广告来源名称: \(adSourceName)") // 输出广告来源名称
                }
                if let mediationGroupName = mediationGroupName {
                   // adLog("xianban: 中介组名称: \(mediationGroupName)") // 输出中介组名称
                }
                if let mediationABTestName = mediationABTestName {
                  //  adLog("xianban: 中介 AB 测试名称: \(mediationABTestName)") // 输出中介 AB 测试名称
                }
                if let mediationABTestVariant = mediationABTestVariant {
                   // adLog("xianban: 中介 AB 测试变体: \(mediationABTestVariant)") // 输出中介 AB 测试变体
                }
            }
            adLog("将展示开屏广告。")
            isShowingAd = true
            ad.present(fromRootViewController: nil)
        }


    
    }
}

extension AppOpenAdManager: GADFullScreenContentDelegate {
    func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        adLog("将展示开屏广告。")
    }
    
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        
        appOpenAd = nil
        isShowingAd = false
        adLog("开屏广告已被关闭。")
        adDidClose()
        appOpenAdManagerAdDidComplete()
        
        /**
         记录当日广告展示次数
         广告展示总数
         */
    
     //logData(position: "open", status: "开屏广告", uid: myadID, info: "开屏广告价值", currency: mycu, cicros: myci)
        Task {
            await loadAd()
        }
    }
    
    private func adDidClose() {
        adClosed = true
        delegate?.appOpenAdManagerAdDidComplete(self)
    }
    
    
    func ad(
        _ ad: GADFullScreenPresentingAd,
        didFailToPresentFullScreenContentWithError error: Error
    ) {
        appOpenAd = nil
        isShowingAd = false
        appOpenAdManagerAdDidComplete()
        Task {
            await loadAd()
        }
    }
}

